﻿using NxStoreManage;

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;

namespace GeusoftWareDigitalCertificate
{
    public class DigitalCertificate
    {
        public static void Create(List<StoreName> storeNames)
        {
            foreach (var item in storeNames)
            {
                ImPort(item);
            }
            if (suc > 0)
            {
                BaseForm.ShowMsg("证书导入成功！");
            }
        }

        private static bool isAllImport = false;
        private static int suc = 0;

        private static void ImPort(StoreName storeName)
        {
            X509Store rootStore = new X509Store(storeName, StoreLocation.LocalMachine);//获取本地计算机受信任的根证书的储存区
            rootStore.Open(OpenFlags.MaxAllowed); //查找证书前，一定要打开
            X509Certificate2Collection collection = rootStore.Certificates;//获取储存区上的所有证书
            //DigiCert Global Root CA,Thumbprint: A8985D3A65E5E5C4B2D7D66D40C6DD2FB19C5436
            string Thumbprint = "ceef50f18f98635223e47b42d7e577632966f8fc";
            //按指纹查找，系统是否内置了这个根证书
            X509Certificate2Collection fcollection = collection.Find(X509FindType.FindByThumbprint, Thumbprint, false);
            try
            {
                if (fcollection != null && fcollection.Count == 0)
                {
                    if (!isAllImport)
                    {
                        DialogResult dr = MessageBox.Show("是否导入《南京好易信息技术有限公司》数字证书？", "", MessageBoxButtons.YesNo);
                        if (dr == DialogResult.No)
                            return;
                        else
                        {
                            isAllImport = true;
                        }
                    }
                    string crtFullName = Path.Combine(Application.StartupPath, "geusoftware.cer");
                    if (File.Exists(crtFullName))
                    {
                        X509Certificate2 x509 = new X509Certificate2(crtFullName);
                        rootStore.Add(x509);
                        suc++;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                rootStore.Close();
            }
        }
    }
}